package com.msb.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author sunpeng
 * @Date 2021-06-07 13:19
 */
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor preHandle");
        /*设置请求和响应的乱码 */
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //token校验等等
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor postHandle");

        //过滤返回的敏感字
        Map<String, Object> model = modelAndView.getModel();
        String msg = (String)model.get("msg");
        String newMsg = msg.replace("脏话", "**");
        model.put("msg", newMsg);

        //新的跳转页面
//        modelAndView.setViewName("/index.jsp");
    }

    //无论controller是否出现异常,都会执行的方法，一般来说都做一些资源释放工作
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor afterCompletion");
        System.out.println(ex);
    }
}
